package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"user/model/mysql"
	"user/model/redisInit"
	"user/pkg"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *userrpc.UserUpdateRequest) (*userrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("username = ?", in.Username).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号为空,请重试登录")
	}
	get := redisInit.Client.Get("sendSms" + in.SendSms + in.Username)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	if pkg.MD5(in.Password) == user.Password {
		return nil, fmt.Errorf("修改后密码,不允许与原密码相同")
	}
	if in.Username != user.Username {
		return nil, fmt.Errorf("两次密码输入不一致,请重新输入")
	}
	m := mysql.User{
		Model:     gorm.Model{ID: user.ID},
		Username:  user.Username,
		Password:  pkg.MD5(user.Password),
		Origin:    user.Origin,
		Age:       user.Age,
		Email:     user.Email,
		HeadImage: user.HeadImage,
	}
	//user := mysql.User{}
	//err := mysql.DB.Debug().Updates(&user).Error
	//if err != nil {
	//	return nil, fmt.Errorf("用户修改失败")
	//}
	err := mysql.DB.Debug().Where("ID = ?", user.ID).Updates(&m).Error
	if err != nil {
		return nil, fmt.Errorf("用户完善失败")
	}
	return &userrpc.UserUpdateResponse{
		Id: int64(m.ID),
	}, nil
}
